package com.pur.zsms.quotation.web;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.cglib.beans.BeanCopier;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.pur.zsms.accountmanage.vo.AccountVo;
import com.pur.zsms.check.vo.CheckVo;
import com.pur.zsms.common.exception.GenericException;
import com.pur.zsms.common.support.PageController;
import com.pur.zsms.common.support.PaginationSupport;
import com.pur.zsms.common.util.ExcelReader;
import com.pur.zsms.common.util.FileUtill;
import com.pur.zsms.common.util.PubFun;
import com.pur.zsms.documentsmanage.vo.DomVo;
import com.pur.zsms.lockmanage.service.ILockTransService;
import com.pur.zsms.matermanage.mater.vo.MaterVo;
import com.pur.zsms.ordercustommanage.po.OrderSupplierMaterPo;
import com.pur.zsms.ordercustommanage.vo.ExcelVo;
import com.pur.zsms.ordercustommanage.vo.OrderCustVo;
import com.pur.zsms.ordercustommanage.vo.SelectFoodVo;
import com.pur.zsms.pmsnmanage.menu.po.MenuPo;
import com.pur.zsms.pmsnmanage.role.vo.RoleVo;
import com.pur.zsms.pmsnmanage.user.po.UserPo;
import com.pur.zsms.pmsnmanage.user.po.UserRolePo;
import com.pur.zsms.pmsnmanage.user.service.IUserService;
import com.pur.zsms.pmsnmanage.user.vo.UserVo;
import com.pur.zsms.pmsnmanage.user.web.UserControllor;
import com.pur.zsms.quotation.po.QuotationPo;
import com.pur.zsms.quotation.po.QuotationSubPo;
import com.pur.zsms.quotation.service.IQuotationService;
import com.pur.zsms.quotation.vo.QuotationVo;
import com.pur.zsms.supplier.po.ShopSupplierTypePo;
import com.pur.zsms.supplier.po.SupplierPo;
import com.pur.zsms.supplier.service.ISupplierService;
import com.pur.zsms.supplier.vo.ShopSupplierVo;
import com.pur.zsms.supplier.vo.SupplierDistributeVo;
import com.pur.zsms.supplier.vo.SupplierOrderCustVo;
import com.pur.zsms.supplier.vo.SupplierQualificationVo;
import com.pur.zsms.supplier.vo.SupplierVo;
import com.pur.zsms.systemsetting.datadictionary.po.Code;
import com.pur.zsms.systemsetting.datadictionary.vo.CodeVo;
import com.pur.zsms.timecontrol.service.ITimeControlService;

/**
 * 供应商控制器
 * 
 * @author yuxin
 * 
 */
@Controller
@RequestMapping(value = "/quotationCust")
public class QuotationCustController {
	@SuppressWarnings("unused")
	private static final Logger log = LoggerFactory.getLogger(QuotationCustController.class);
	protected int page = 1;

	protected int pageSize = 15;

	PaginationSupport pageList;

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	@Resource(name = "supplierService")
	private ISupplierService supplierService;

	@Resource(name = "timeControlService")
	private ITimeControlService timeControlService;

	@Resource(name = "userService")
	private IUserService userService;

	@Resource(name = "lockTransService")
	private ILockTransService lockTransService;

	@Resource(name = "quotationService")
	private IQuotationService quotationService;

	// 客户报价单
	@RequestMapping(value = "/quotationCustForSupplier.do", method = { RequestMethod.POST })
	@ResponseBody
	public String quotationCustForSupplier(HttpServletRequest request, HttpServletResponse response, HttpSession session1, String orderDate,
			int supId, String datejson) {
		JSONObject json = new JSONObject();
		Map<String, BigDecimal> materTypeMap = new HashMap<String, BigDecimal>();

		if (!"undefined".equals(datejson) && !"".equals(datejson) && datejson != null) {

			JSONArray array = JSONArray.fromObject(datejson);
			for (int i = 0; i < array.size(); i++) {
				JSONObject object = JSONObject.fromObject(array.get(i));
				materTypeMap.put(object.get("materType").toString(),
						new BigDecimal(object.get("raiseAmount").toString()).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP));
			}
		}

		HttpSession session = request.getSession();
		session.setAttribute("state", null);
		// 生成提示信息，
		String codedFileName = null;
		String codedFileNameUser = null;

		OutputStream fOut = null;
		UserPo userInfo = (UserPo) session1.getAttribute("user");

		try {

			response.setContentType("application/vnd.ms-excel");

			// 根据用户id得出supid

			if (supId == 0) {
				supId = supplierService.getSupIdByUserId(userInfo.getUserId());
			}
			// 进行转码，使其支持中文文件名
			// codedFileName = java.net.URLEncoder.encode("Quotation" + supId +
			// "_" + orderDate, "UTF-8");
			codedFileName = new String("报价单".getBytes("GBK"), "ISO8859-1");
			response.setHeader("content-disposition", "attachment;filename=" + codedFileName + ".xls");
			// response.addHeader("Content-Disposition",
			// "attachment;   filename=" + codedFileName + ".xls");
			// 产生工作簿对象
			HSSFWorkbook workbook = new HSSFWorkbook();

			// 产生工作表对象

			HSSFSheet sheet = workbook.createSheet();

			org.apache.poi.ss.util.CellRangeAddress c = CellRangeAddress.valueOf("A1:H1");
			sheet.setAutoFilter(c);

			// 设定自动适应列宽
			/*
			 * for (int i = 0; i < 20; i++) { sheet.autoSizeColumn(i); }
			 */
			// 边框
			HSSFCellStyle setBorder = workbook.createCellStyle();
			setBorder.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
			setBorder.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
			setBorder.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
			setBorder.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框
			setBorder.setAlignment(HSSFCellStyle.VERTICAL_CENTER);
			// sheet.setColumnHidden(0, true);// 隐藏列
			/*
			 * sheet.setColumnHidden(1, true);// 隐藏列 sheet.setColumnHidden(2,
			 * true);// 隐藏列 sheet.setColumnHidden(3, true);// 隐藏列
			 * sheet.setColumnHidden(4, true);// 隐藏列
			 */
			int sheetIndex = 0;
			// 初始行设置
			HSSFRow rowfist = sheet.createRow((int) 0);// 创建一行
			rowfist.setHeight((short) 340);// 行高

			int totalLine = 0;

			HSSFCell cellFirst1 = rowfist.createCell(totalLine);// 创建一列
			cellFirst1.setCellType(HSSFCell.CELL_TYPE_STRING);
			cellFirst1.setCellValue("材料Id");
			cellFirst1.setCellStyle(setBorder);
			totalLine = totalLine + 1;

			HSSFCell cellFirst7 = rowfist.createCell(totalLine);// 创建一列
			cellFirst7.setCellType(HSSFCell.CELL_TYPE_STRING);
			cellFirst7.setCellValue("最后报价时间");
			cellFirst7.setCellStyle(setBorder);
			totalLine = totalLine + 1;

			HSSFCell cellFirst10 = rowfist.createCell(totalLine);// 创建一列
			cellFirst10.setCellType(HSSFCell.CELL_TYPE_STRING);
			cellFirst10.setCellValue("种类");
			cellFirst10.setCellStyle(setBorder);
			totalLine = totalLine + 1;

			HSSFCell cellFirst12 = rowfist.createCell(totalLine);// 创建一列
			cellFirst12.setCellType(HSSFCell.CELL_TYPE_STRING);
			cellFirst12.setCellValue("品牌");
			cellFirst12.setCellStyle(setBorder);
			totalLine = totalLine + 1;

			HSSFCell cellFirst13 = rowfist.createCell(totalLine);// 创建一列
			cellFirst13.setCellType(HSSFCell.CELL_TYPE_STRING);
			cellFirst13.setCellValue("规格");
			cellFirst13.setCellStyle(setBorder);
			totalLine = totalLine + 1;

			HSSFCell cellFirst2 = rowfist.createCell(totalLine);// 创建一列
			cellFirst2.setCellType(HSSFCell.CELL_TYPE_STRING);
			cellFirst2.setCellValue("材料名");
			cellFirst2.setCellStyle(setBorder);
			totalLine = totalLine + 1;

			HSSFCell cellFirst8 = rowfist.createCell(totalLine);// 创建一列
			cellFirst8.setCellType(HSSFCell.CELL_TYPE_STRING);
			cellFirst8.setCellValue("单位价格");
			cellFirst8.setCellStyle(setBorder);
			totalLine = totalLine + 1;

			HSSFCell cellFirst11 = rowfist.createCell(totalLine);// 创建一列
			cellFirst11.setCellType(HSSFCell.CELL_TYPE_STRING);
			cellFirst11.setCellValue("单位");
			cellFirst11.setCellStyle(setBorder);
			totalLine = totalLine + 1;

			// 根据日期取得 总表数据
			List<Object[]> listTotal = supplierService.getCustQuotationDate(supId);

			for (int i = 0; i < listTotal.size(); i++) {

				Object[] a = listTotal.get(i);
				HSSFRow row = sheet.createRow((int) i + 1);// 创建一行
				row.setHeight((short) 340);// 行高

				int totalDateLine = 0;

				HSSFCell cell1 = row.createCell(totalDateLine);// 创建一列 材料Id
				cell1.setCellType(HSSFCell.CELL_TYPE_STRING);
				cell1.setCellValue(a[0].toString());
				cell1.setCellStyle(setBorder);
				totalDateLine = totalDateLine + 1;

				HSSFCell cell3 = row.createCell(totalDateLine);// 创建一列 材料品级
				cell3.setCellType(HSSFCell.CELL_TYPE_STRING);
				if (a[1] == null) {
					cell3.setCellValue("");
				} else {
					cell3.setCellValue(a[1].toString());
				}
				cell3.setCellStyle(setBorder);
				totalDateLine = totalDateLine + 1;

				HSSFCell cell4 = row.createCell(totalDateLine);// 创建一列 供货商ID
				cell4.setCellType(HSSFCell.CELL_TYPE_STRING);
				cell4.setCellValue(a[2].toString());
				cell4.setCellStyle(setBorder);
				totalDateLine = totalDateLine + 1;

				HSSFCell cell5 = row.createCell(totalDateLine);// 创建一列 供货商name
				cell5.setCellType(HSSFCell.CELL_TYPE_STRING);
				cell5.setCellValue(a[3].toString());
				cell5.setCellStyle(setBorder);
				totalDateLine = totalDateLine + 1;

				HSSFCell cell7 = row.createCell(totalDateLine);// 创建一列 时间
				cell7.setCellType(HSSFCell.CELL_TYPE_STRING);
				cell7.setCellValue(a[4].toString());
				cell7.setCellStyle(setBorder);
				totalDateLine = totalDateLine + 1;

				HSSFCell cell9 = row.createCell(totalDateLine);// 创建一列 时间
				cell9.setCellType(HSSFCell.CELL_TYPE_STRING);
				cell9.setCellValue(a[5].toString());
				cell9.setCellStyle(setBorder);
				totalDateLine = totalDateLine + 1;

				HSSFCell cell8 = row.createCell(totalDateLine);// 创建一列 每公斤价格
				cell8.setCellType(HSSFCell.CELL_TYPE_STRING);
				cell8.setCellStyle(setBorder);
				if (a[6] == null) {
					cell8.setCellValue("");
				} else {
					BigDecimal materValue = new BigDecimal(a[6].toString()).multiply(new BigDecimal(1000)).setScale(2, BigDecimal.ROUND_HALF_UP);
					if (materTypeMap.containsKey(a[8].toString())) {
						materValue = materValue.multiply(materTypeMap.get(a[8].toString())).setScale(2, BigDecimal.ROUND_HALF_UP);
					}
					cell8.setCellValue(materValue.toString());
				}
				totalDateLine = totalDateLine + 1;

				HSSFCell cel20 = row.createCell(totalDateLine);// 创建一列 时间
				cel20.setCellType(HSSFCell.CELL_TYPE_STRING);
				cel20.setCellValue(a[7].toString());
				cel20.setCellStyle(setBorder);
				totalDateLine = totalDateLine + 1;

			}

			workbook.setSheetName(sheetIndex, "报价单");
			sheet.setForceFormulaRecalculation(true);
			fOut = response.getOutputStream();
			workbook.write(fOut);
		} catch (UnsupportedEncodingException e1) {
		} catch (Exception e) {
		} finally {
			try {
				fOut.flush();
				fOut.close();
			} catch (IOException e) {
				json.put("success", false);
			}
			session.setAttribute("state", "open");
		}

		json.put("success", true);
		return json.toString();
	}

	@RequestMapping(value = "/saveQuotation.do", method = { RequestMethod.POST })
	@ResponseBody
	public String saveQuotation(String datejson, HttpSession session, String quotationName) {
		JSONObject json = new JSONObject();
		UserPo userInfo = (UserPo) session.getAttribute("user");
		try {
			long supId = supplierService.getSupIdByUserId(userInfo.getUserId());
			boolean flag = quotationService.checkSaveQuotation(quotationName, supId);
			if (!flag) {
				json.put("msg", quotationService.getMsg());
				json.put("success", false);
			}

			QuotationPo quotationPo = quotationService.saveQuotation(quotationName, supId);

			JSONArray array = JSONArray.fromObject(datejson);
			for (int i = 0; i < array.size(); i++) {
				JSONObject object = JSONObject.fromObject(array.get(i));
				QuotationSubPo quotationSubPo = new QuotationSubPo();
				quotationSubPo.setQuotationId(quotationPo.getQuotationId());
				quotationSubPo.setMaterType(Integer.valueOf(object.get("materType").toString()));
				quotationSubPo.setRaiseAmount(object.get("raiseAmount").toString());
				quotationSubPo.setOrderId(Integer.valueOf(object.get("orderId").toString()));
				quotationService.saveQuotationSub(quotationSubPo);
			}

		} catch (GenericException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		json.put("success", true);
		return json.toString();
	}

	@RequestMapping(value = "/findQuotation.do", method = { RequestMethod.POST })
	@ResponseBody
	public String findQuotation(@RequestParam(required = false) String page, @RequestParam(required = false) String rows, QuotationVo quotationVo)
			throws GenericException {
		JSONObject json = new JSONObject();
		if (page == null || page.equals(""))
			page = "1";
		if (rows == null || rows.equals(""))
			rows = "10";
		List<QuotationVo> tQuotationVoList = new ArrayList<QuotationVo>();

		if (quotationVo.getQuotationId() == 0) {
			json.put("success", false);
			json.put("total", 0);
			json.put("rows", tQuotationVoList);
			return json.toString();
		}
		PageController pageController = new PageController(Integer.parseInt(page), Integer.parseInt(rows));
		this.pageList = quotationService.listQuotation(pageController, quotationVo);
		List items = pageList.getItems();
		if (items != null) {
			for (int i = 0; i < items.size(); i++) {
				Object[] item = (Object[]) items.get(i);
				QuotationVo f = new QuotationVo();
				f.setOrderId((Integer) item[0]);
				f.setMaterType((Integer) item[1]);
				f.setRaiseAmount(item[2].toString());
				tQuotationVoList.add(f);
			}
		}
		json.put("success", true);
		json.put("total", pageList.getTotalCount());
		json.put("rows", tQuotationVoList);
		return json.toString();
	}

	@RequestMapping(value = "/pullDownQuotation.do", method = { RequestMethod.POST })
	@ResponseBody
	public String pullDownQuotation(HttpSession session) {
		UserPo userInfo = (UserPo) session.getAttribute("user");
		String userLevelString = "";
		try {
			long supId = supplierService.getSupIdByUserId(userInfo.getUserId());
			userLevelString = quotationService.pullDownQuotation("quotationId", "quotationName", supId);
		} catch (GenericException e) {
			e.printStackTrace();
		}
		return userLevelString;
	}

	@RequestMapping(value = "/deleteQuotation.do", method = { RequestMethod.POST })
	@ResponseBody
	public String deleteQuotation(HttpSession session, long quotationId) {
		JSONObject json = new JSONObject();
		try {
			quotationService.deleteQuotation(quotationId);
		} catch (GenericException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		json.put("success", true);
		return json.toString();
	}
}
